#!/bin/bash

# 学生荣誉信息管理系统 - 数据库迁移脚本
# 用于执行数据库迁移和更新

echo "=========================================="
echo "学生荣誉信息管理系统 - 数据库迁移"
echo "=========================================="

# 设置环境变量
export FLASK_APP=wsgi.py
export FLASK_ENV=development

# 检查Python环境
echo "检查Python环境..."
python --version

# 检查Flask是否安装
echo "检查Flask环境..."
python -c "import flask; print('Flask版本:', flask.__version__)"
python -c "import flask_migrate; print('Flask-Migrate已安装')"

# 检查当前目录
echo "当前工作目录: $(pwd)"

# 检查wsgi.py文件是否存在
if [ ! -f "wsgi.py" ]; then
    echo "错误: wsgi.py文件不存在，请确保在项目根目录下运行此脚本"
    exit 1
fi

# 检查migrations目录是否存在
if [ ! -d "migrations" ]; then
    echo "错误: migrations目录不存在"
    echo "请先运行 init_db.sh 进行数据库初始化"
    exit 1
fi

# 显示当前迁移状态
echo "当前迁移状态:"
flask db current

echo "迁移历史:"
flask db history

# 询问用户是否继续
read -p "是否继续执行数据库迁移? (y/N): " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo "取消操作"
    exit 0
fi

# 执行数据库迁移
echo "开始生成迁移文件..."
flask db migrate -m "数据库迁移 $(date '+%Y-%m-%d %H:%M:%S')"

if [ $? -eq 0 ]; then
    echo "迁移文件生成成功!"
    
    # 显示生成的迁移文件
    echo "生成的迁移文件:"
    ls -la migrations/versions/ | tail -5
    
    # 询问是否立即应用迁移
    read -p "是否立即应用迁移到数据库? (y/N): " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        echo "开始应用迁移到数据库..."
        flask db upgrade
        
        if [ $? -eq 0 ]; then
            echo "=========================================="
            echo "数据库迁移成功!"
            echo "所有表已创建并更新"
            echo "=========================================="
            
            # 显示当前迁移状态
            echo "当前迁移状态:"
            flask db current
            
        else
            echo "=========================================="
            echo "数据库迁移失败!"
            echo "请检查以下可能的问题:"
            echo "1. 数据库连接是否正常"
            echo "2. 数据库用户是否有足够权限"
            echo "3. 数据库服务器是否可访问"
            echo "=========================================="
            exit 1
        fi
    else
        echo "=========================================="
        echo "迁移文件已生成，但未应用到数据库"
        echo "您可以稍后手动运行: flask db upgrade"
        echo "=========================================="
    fi
else
    echo "=========================================="
    echo "迁移文件生成失败!"
    echo "请检查模型定义是否正确"
    echo "=========================================="
    exit 1
fi 